package com.lfg.leetcode.leetcode0;

import java.util.ArrayList;
import java.util.List;

public class No68fullJustify {

    public static void main(String[] args) {
        List<String> ret = fullJustify(new String[]{"This", "is", "an", "example", "of", "text", "justification."}, 16);
        for (String str : ret) {
            System.out.println("[" + str + "]");
        }
    }

    public static List<String> fullJustify(String[] words, int maxWidth) {
        List<String> ret = new ArrayList<>();
        int total = 0;
        int index = 0;
        int i = 0;
        for (; i < words.length; i++) {
            total += words[i].length();
            if (i - index > 0) {
                total++;
            }
            if (total > maxWidth) {
                int cnt = i - index - 1;
                int length = total - words[i].length();
                if (i - index > 0) {
                    length--;
                }
                int bl = maxWidth - length + cnt;
                int av = bl;
                int other = 0;
                if (cnt > 1) {
                    av = bl / cnt;
                    other = bl % cnt;
                }
                StringBuilder sb = new StringBuilder();
                for (; index < i; index++) {
                    sb.append(words[index]);
                    int tmp = av;
                    while (tmp > 0 && index < i - 1) {
                        sb.append(" ");
                        tmp--;
                    }
                    while (tmp > 0 && cnt <= 0) {
                        sb.append(" ");
                        tmp--;
                    }
                    if (other-- > 0 && index < i - 1) {
                        sb.append(" ");
                    }
                }
                ret.add(sb.toString());
                total = words[i].length();
            }

        }
        StringBuilder sb = new StringBuilder();
        total = 0;
        for (; index < i; index++) {
            sb.append(words[index]);
            total += words[index].length();
            if (total < maxWidth) {
                sb.append(" ");
                total += 1;
            }
        }
        for (; total < maxWidth; total++) {
            sb.append(" ");
        }
        ret.add(sb.toString());
        return ret;
    }
}

